<template>
  <div>
    <terminalProperties-header
      title="设备终端"
      @getTime="handleGetTime"
      @getChannel="handleGetChannel"
      @getVersion="handleGetVersion"
    >
      <div slot="changeOptions">
        <a-radio-group v-model="headerValue" @change="onChangeHeader">
          <a-radio-button value="a"> 机型 </a-radio-button>
          <!-- <a-radio-button value="b" disabled> 分辨率 </a-radio-button> -->
          <a-radio-button value="c"> 操作系统 </a-radio-button>
        </a-radio-group>
      </div>
    </terminalProperties-header>
    <div class="deviceTerminal-container">
      <div class="deviceTerminal-title">
        <span>Top10{{ deviceTerminalTitle }}</span>
      </div>
      <div class="deviceTerminal-tabs">
        <!-- <a-tabs default-active-key="1" @change="callback"> -->
        <a-tabs v-model="tabsKey" @change="callback">
          <a-tab-pane key="1" tab="新增用户">
            <div class="chart-wrapper">
              <histogram-chart
                :name="deviceTerminalTitle"
                tooltipName="新增人数"
                :xAxisName="xAxisNameNewAdd"
                :height="hourHeight"
                :chartData="chartData"
              />
            </div>
          </a-tab-pane>
          <a-tab-pane key="2" tab="启动次数">
            <div class="chart-wrapper">
              <histogram-chart
                :name="deviceTerminalTitle"
                tooltipName="启动次数"
                :height="hourHeight"
                :chartData="chartData"
                :xAxisName="xAxisNameCount"
              />
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
      <el-link
        style="margin-left: 16px"
        @click="changePutAwayStatus"
        type="primary"
        :underline="false"
        >{{ putAwayName }}明细数据<i
          :class="[
            isPutAway ? 'el-icon-arrow-up' : 'el-icon-arrow-down',
            'el-icon--right',
          ]"
        ></i
      ></el-link>
      <div class="deviceTerminal-tables">
        <a-table
          v-if="isPutAway"
          :pagination="pagination"
          rowKey="id"
          :columns="columns"
          :data-source="data"
          @change="onChangePagination"
        ></a-table>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import TerminalPropertiesHeader from "@/components/TerminalPropertiesHeader";
import HistogramChart from "@/echartsComponent/HistogramChart.vue";
import { getYearMonthDayFromOne, getYearMonthDay } from "@/utils/functions";
import {
  // getGmDevice, // 废弃
  getNewUserAddCountByDeviceModel,
  getStartUpCountInDeviceModel,
  getNewUserAddCountByDeviceOS,
  getStartUpCountInDeviceOS,
} from "@/api/deviceTerminal";

function onChangePagination(pagination, filters, sorter) {
  console.log("params", pagination, filters, sorter);
}

export default {
  name: "DeviceTerminal",
  data() {
    return {
      tabsKey: "1",
      headerValue: "a",
      hourHeight: "400px",
      chartData: {
        xAxisData: [],
        yAxisData: [],
        yAnnotationAxisData: []
      },
      isPutAway: true,
      data: [],
      loading: false,
      pagination: {
        pageSize: 10,
        total: 0,
      },
      selectData: {
        startDate: null,
        endDate: null,
        channel: null,
        version: null,
        appKey: "",
        current: 1,
        size: 10,
      },
    };
  },
  components: {
    TerminalPropertiesHeader,
    HistogramChart,
  },
  computed: {
    deviceTerminalTitle() {
      let title = '';
      if (this.headerValue == "a") {
        title = '机型'
      } else if (this.headerValue == 'c') {
        title = '操作系统'
      }
      return title
    },
    columns() {
      let columnsRes = [
        {
          title: "机型",
          dataIndex: "deviceModel",
        },
        {
          title: "新增用户数",
          dataIndex: "count",
        },
      ];
      if (this.headerValue == "a") {
        columnsRes.push({
          title: "品牌",
          dataIndex: "deviceBrand",
        },
        {
          title: "系列",
          dataIndex: "deviceSerial",
        })
        if (this.tabsKey == "2") {
          columnsRes[1]["title"] = "启动次数";
        }
      } else if (this.headerValue == "c") {
        if (this.tabsKey == "1") {
          columnsRes[0]["title"] = "操作系统";
          columnsRes[0]["dataIndex"] = "os";
        } else if (this.tabsKey == "2") {
          columnsRes[0]["title"] = "操作系统";
          columnsRes[0]["dataIndex"] = "os";
          columnsRes[1]["title"] = "启动次数";
        }
      }
      return columnsRes;
    },
    putAwayName() {
      return this.isPutAway ? "收起" : "展开";
    },
    xAxisNameNewAdd() {
      return (
        this.selectData.startDate +
        "-" +
        this.selectData.endDate +
        " " +
        "新增用户"
      );
    },
    xAxisNameCount() {
      return (
        this.selectData.startDate +
        "-" +
        this.selectData.endDate +
        " " +
        "启动次数"
      );
    },
    ...mapGetters(["applicationId"]),
  },
  methods: {
    onChangePagination,
    changePutAwayStatus() {
      this.isPutAway = !this.isPutAway;
    },
    async callback(key) {
      await this.getChartsDataFromServer();
    },
    async onChangeHeader(e) {
      await this.getChartsDataFromServer();
    },
    async handleGetTime(msg) {
      this.selectData.startDate = msg[0];
      this.selectData.endDate = msg[1];
      await this.getChartsDataFromServer();
    },
    async handleGetChannel(msg) {
      this.selectData.channel = msg.key;
      await this.getChartsDataFromServer();
    },
    async handleGetVersion(msg) {
      this.selectData.version = msg.key;
      await this.getChartsDataFromServer();
    },
    // 废弃
    // 2021-06-08暂时先不做列表
    // async getDataFromServer() {
    //   this.loading = true;
    //   let res;
    //   try {
    //     res = await getGmDevice(this.selectData);
    //   } catch (error) {
    //     this.loading = false;
    //     console.log(error);
    //   }
    //   this.loading = false;
    //   let { code } = res;
    //   if (code == 0) {
    //     // 做些什么
    //     this.listData = res.data.records;
    //     this.pagination.total = res.data.total;
    //   }
    // },
    // 请求折线图数据
    async getChartsDataFromServer() {
      let actionFunc = {
        a: {
          1: getNewUserAddCountByDeviceModel,
          2: getStartUpCountInDeviceModel,
        },
        c: {
          1: getNewUserAddCountByDeviceOS,
          2: getStartUpCountInDeviceOS,
        },
      };
      // 每次请求，清空数据
      this.chartData.xAxisData.length = 0;
      this.chartData.yAxisData.length = 0;
      this.chartData.yAnnotationAxisData.length = 0;
      let res;
      try {
        res = await actionFunc[this.headerValue][this.tabsKey](this.selectData);
      } catch (error) {
        console.log(error);
      }
      let { code } = res;
      if (code == 0) {
        // 做些什么
        if (res.data.length == 0) {
          this.chartData.xAxisData = [];
          this.chartData.yAxisData = [];
          this.chartData.yAnnotationAxisData.length = 0;
          this.data = [];
          this.pagination.total = 0;
        } else {
          let newData = JSON.parse(JSON.stringify(res.data));
          newData = newData.sort(function (a, b) {
            return a.count - b.count;
          });
          newData.forEach((item, index) => {
            item["id"] = index;
            if (this.headerValue == "a") {
              this.chartData.yAxisData.push(item.deviceModel);
              this.chartData.yAnnotationAxisData.push(item.deviceSerial);
            } else if (this.headerValue == "c") {
              this.chartData.yAxisData.push(item.os);
            }
            this.chartData.xAxisData.push(item.count);
          });
          this.data = newData.sort(function (a, b) {
            return b.count - a.count;
          });
          this.pagination.total = newData.length;
        }
      }
      console.log(this.chartData, '@@@@@@@@@@@@')
    },
    // 折线图
    async getNewUserAddCountByDeviceModelFromServer(data) {
      // 每次请求，清空数据
      this.chartData.xAxisData.length = 0;
      this.chartData.yAxisData.length = 0;
      this.chartData.yAnnotationAxisData.length = 0;
      let res;
      try {
        res = await getNewUserAddCountByDeviceModel(data);
      } catch (error) {
        console.log(error);
      }
      let { code } = res;
      if (code == 0) {
        // 做些什么
        if (res.data.length == 0) {
          this.chartData.xAxisData = [];
          this.chartData.yAxisData = [];
          this.chartData.yAnnotationAxisData = [];
          this.data = [];
          this.pagination.total = 0;
        } else {
          let newData = JSON.parse(JSON.stringify(res.data));
          newData = newData.sort(function (a, b) {
            return a.count - b.count;
          });
          newData.forEach((item, index) => {
            item["id"] = index;
            this.chartData.xAxisData.push(item.count);
            this.chartData.yAxisData.push(item.deviceModel);
            this.chartData.yAnnotationAxisData.push(item.deviceSerial);
          });
          this.data = newData.sort(function (a, b) {
            return b.count - a.count;
          });
          this.pagination.total = newData.length;
        }
      }
    },
    async getStartUpCountInDeviceModelFromServer(data) {
      // 每次请求，清空数据
      this.chartData.xAxisData.length = 0;
      this.chartData.yAxisData.length = 0;
      this.chartData.yAnnotationAxisData.length = 0;
      let res;
      try {
        res = await getStartUpCountInDeviceModel(data);
      } catch (error) {
        console.log(error);
      }
      let { code } = res;
      if (code == 0) {
        // 做些什么
        if (res.data.length == 0) {
          this.chartData.xAxisData = [];
          this.chartData.yAxisData = [];
          this.chartData.yAnnotationAxisData = [];
          this.data = [];
          this.pagination.total = 0;
        } else {
          let newData = JSON.parse(JSON.stringify(res.data));
          newData = newData.sort(function (a, b) {
            return a.count - b.count;
          });
          newData.forEach((item, index) => {
            item["id"] = index;
            this.chartData.xAxisData.push(item.count);
            this.chartData.yAxisData.push(item.deviceModel);
            this.chartData.yAnnotationAxisData.push(item.deviceSerial);
          });
          this.data = newData.sort(function (a, b) {
            return b.count - a.count;
          });
          this.pagination.total = newData.length;
        }
      }
    },
  },
  async mounted() {
    this.selectData.appKey = this.applicationId;
    this.selectData.startDate = getYearMonthDayFromOne();
    this.selectData.endDate = getYearMonthDay();
    await Promise.all([this.getChartsDataFromServer()]);
  },
};
</script>

<style lang="scss" scoped>
.deviceTerminal-container {
  margin: 24px 22px 20px;
  padding: 24px;
  background: #fff;
  border-radius: 5px;
  overflow: hidden;
  .deviceTerminal-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 32px;
    color: #000;
  }
  .deviceTerminal-tabs {
    position: relative;
    >>> .ant-tabs {
      .ant-tabs-bar {
        border-bottom: none;
        .ant-tabs-nav-container {
          .ant-tabs-nav-wrap {
            .ant-tabs-tab {
              padding: 12px 0;
            }
            .ant-tabs-ink-bar {
              width: 56px;
            }
          }
        }
      }
    }
    // chart
    .chart-wrapper {
      background: #fff;
      padding: 5px 0 0 16px;
      margin-bottom: 32px;
    }
  }
  .deviceTerminal-tables {
    margin: 24px 0;
  }
}
</style>

